package com.lantu.draw.framework;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.PreResultListener;

public class PreResultHandle implements PreResultListener{
	private final static Logger logger = LoggerFactory.getLogger(PreResultHandle.class);
	@Override
	public void beforeResult(ActionInvocation invocation, String resultCode) {
		Map fieldErrors = (Map) invocation
				.getInvocationContext().getValueStack()
				.findValue("fieldErrors");
		Iterator it_key = fieldErrors.keySet().iterator();
		StringBuilder sb=new StringBuilder();
		while (it_key.hasNext()) {
			 String str = (String)it_key.next();
			 sb.append(((java.util.List<String>)fieldErrors.get(str)).get(0));
			 sb.append("\t\n");
			
		}
		
		// 把fieldErrors放到结果集中，从而返回给前台页面
		// ((JSONResult)(invocation.getResult()))
		 if(sb.length()>0){
			logger.error(sb.toString());
			Object ac = invocation.getAction();
			Class cls = ac.getClass();
			try {
				Method m = cls.getMethod("getReplyMap");
				Map replyMap;
				replyMap = (Map) m.invoke(ac);
				replyMap.put("code", "0");
				replyMap.put("desc", sb.toString());
			} catch (NoSuchMethodException | SecurityException e) {
				logger.error("inner error",e);
			}catch (IllegalAccessException | IllegalArgumentException
					| InvocationTargetException e) {
				logger.error("inner error",e);
			}
		 }
	}

}
